import { defineStore } from "pinia"
import { getToken, getUserInfo } from "@/api/login"
import cache from "@/utils/cache"
import { getMenuList } from "@/api/login"
import { handleDynamicRoutes } from "@/utils/routes"
import router, { routes } from "@/router"

export const useLoginStore = defineStore('login', {
  state: () => {
    return {
      token: cache.getCache("token"),
      userInfo: {},
      username: "",
      menus: []
    }
  },
  getters: {
    tokenGetter: state => state.token,
    usernameGetter: state => state.username,
    menusGetter: state => state.menus
  },
  actions: {
    // 登录
    login(values) {
      return new Promise((resolve, reject) => {
        getToken(values).then(res => {
          this.token = res.data.token
          cache.setCache("token", res.data.token)
          resolve(res);
        }).catch(err => {
          reject(err);
        })
      })
    },
    // 获取用户信息
    getUserInfo() {
      return new Promise((resolve, reject) => {
        getUserInfo().then((res) => {
          this.userInfo = res.data
          this.username = res.data.username
          resolve(res)
        }).catch(err => {
          reject(err);
        })
      })
    },
    // 退出登录
    logout() {
      return new Promise((resolve, reject) => {
        // 重置登录信息
        this.reset()
      })
    },
    // 重置
    reset() {
      cache.removeCache('token')
      this.token = ""
      this.userInfo = {}
      this.username = ""
    },
    // 获取菜单
    getMenus() {
      return new Promise((resolve, reject) => {
        getMenuList().then(res => {
          // 动态菜单
          const dynamicRoutes = handleDynamicRoutes(res.data)
          // 防止刷新地址栏 页面跳转到404
          dynamicRoutes.push(
            {
              path: '/:pathMatch(.*)*',
              name: '404',
              component: () => import('@/pages/404/404.vue'),
              hidden: true
            }
          )
          // 注册路由
          dynamicRoutes.forEach(route => {
            router.addRoute(route)
          })
          // 存储pinia
          this.menus = routes.concat(dynamicRoutes)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    }
  },
})
